package com.yao.servlet;

import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;
import org.thymeleaf.util.StringUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * Copyright (C), 2022-2023, 姚兵
 * Author: 32210
 * Date: 2023/2/13 22:45
 * FileName: BaseServlet
 * Description:
 */
public class BaseServlet extends HttpServlet {

    private TemplateEngine templateEngine;

    public TemplateEngine getTemplateEngine() {
        return templateEngine;
    }

    @Override
    public void init() throws ServletException {

        ServletContext servletContext = this.getServletContext();
        ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(servletContext);
        templateResolver.setTemplateMode(TemplateMode.HTML);
        // This will convert "home" to "/WEB-INF/templates/home.html"
        String prefix = servletContext.getInitParameter("view-prefix");
        String suffix = servletContext.getInitParameter("view-suffix");
        templateResolver.setPrefix(StringUtils.isEmpty(prefix)?"/WEB-INF/templates/":prefix);
        templateResolver.setSuffix(StringUtils.isEmpty(suffix)?".html":suffix);
        // Template cache TTL=1h. If not set, entries would be cached until expelled by LRU
        templateResolver.setCacheTTLMs(3600000L);


        templateEngine = new TemplateEngine();
        templateEngine.setTemplateResolver(templateResolver);
    }

    protected void setWebContext(WebContext webContext){

    }
    protected void process(String templateName, HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        WebContext webContext = new WebContext(request,response, request.getServletContext());
        this.templateEngine.process(templateName,webContext,response.getWriter());
    }

    protected void process(String templateName, Map<String,Object> variables, HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        WebContext webContext = new WebContext(request,response, request.getServletContext());
        webContext.setVariables(variables);
        this.templateEngine.process(templateName,webContext,response.getWriter());
    }

}
